import cors from 'cors'
import express from 'express'
import { createServer } from 'http'
import { Server } from 'socket.io'
import { connectDB } from './config/db'
import { errorHandler } from './middleware/errorHandler'
import { generalLimiter } from './middleware/rateLimit'
import { requestLogger } from './middleware/requestLogger'
import { setupSecurity } from './middleware/security'
import routes from './routes'
import { mediaService } from './services/media'
import { initSocketServer } from './services/socket'

const app = express()
const httpServer = createServer(app)
const io = new Server(httpServer, {
  cors: {
    origin: process.env.CLIENT_URL,
    methods: ['GET', 'POST'],
  },
})

// 安全中间件
setupSecurity(app)

// 基础中间件
app.use(express.json({ limit: '10kb' }))
app.use(express.urlencoded({ extended: true, limit: '10kb' }))
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    credentials: true,
  })
)

// 日志和限流
app.use(requestLogger)
app.use('/api', generalLimiter)

// 路由
app.use('/api', routes)

// 错误处理
app.use(errorHandler)

// 初始化服务
const startServer = async () => {
  try {
    // 连接数据库
    await connectDB()

    // 初始化Socket服务
    initSocketServer(io)

    // 启动媒体服务器
    mediaService.start()

    // 启动HTTP服务器
    const port = process.env.PORT || 3000
    httpServer.listen(port, () => {
      console.log(`Server running on port ${port}`)
    })
  } catch (error) {
    console.error('Server startup failed:', error)
    process.exit(1)
  }
}

startServer()

export { app, httpServer, io }
